package com.dqhl.business.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dqhl.business.Base.BaseActivity;
import com.dqhl.business.R;
import com.dqhl.business.modle.GoodsClass;
import com.dqhl.business.modle.ShopInfo;
import com.dqhl.business.util.Config;
import com.dqhl.business.util.Constant;
import com.dqhl.business.util.Dlog;
import com.dqhl.business.util.JsonUtils;
import com.dqhl.business.view.PictureHandlePopupWindow;
import com.dqhl.business.view.PictureSelectPopupWindow;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * description: 资质认证
 * autour: guanluocang
 * date: 2016/11/6 18:24
 */
public class ShopAptitudeActivity extends BaseActivity implements View.OnClickListener {

    private TextView tv_goodsTopTitle;
    private TextView tv_topRight;
    private ImageView iv_goodsGoBack;
    private TextView tv_type; //经营类目
    private ImageView iv_postYingye;//营业执照
    private ImageView iv_postFood;//食品经验许可证
    private ImageView iv_postDoor;//门店照
    private ImageView iv_environment;//店内环境
    private ShopInfo shopInfo; //商户信息
    private GoodsClass goodsClass;
    private LinearLayout ll_foodCard; //食品经验许可证
    private boolean picAisFromNet; //图片来自服务器
    private boolean picBisFromNet; //图片来自服务器
    private boolean picCisFromNet; //图片来自服务器
    private boolean picDisFromNet; //图片来自服务器
    private String pic_1 = "";
    private String pic_2 = "";
    private String pic_3 = "";
    private String pic_4 = "";
    private PictureSelectPopupWindow pictureSelectPopupWindow;
    private PictureHandlePopupWindow pictureHandlePopupWindow;
    private static int REQUESTCODE_PICTURE = 100;
    private static int REQUESTCODE_CAMERA = 101;
    private int TAG = 0;//  标记是那张图片

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_aptitude);
        initView();
        initData();
    }

    private void initView() {
        tv_goodsTopTitle = (TextView) findViewById(R.id.tv_goodsTopTitle);
        tv_goodsTopTitle.setText("资质认证");
        tv_topRight = (TextView) findViewById(R.id.tv_topRight);
        tv_topRight.setVisibility(View.VISIBLE);
        tv_topRight.setText("保存");
        tv_type = (TextView) findViewById(R.id.tv_type);
        iv_goodsGoBack = (ImageView) findViewById(R.id.iv_goodsGoBack);
        iv_postYingye = (ImageView) findViewById(R.id.iv_postYingye);
        iv_postFood = (ImageView) findViewById(R.id.iv_postFood);
        iv_postDoor = (ImageView) findViewById(R.id.iv_postDoor);
        iv_environment = (ImageView) findViewById(R.id.iv_environment);
        ll_foodCard = (LinearLayout) findViewById(R.id.ll_foodCard);

        iv_postYingye.setOnClickListener(this);
        iv_postDoor.setOnClickListener(this);
        iv_environment.setOnClickListener(this);
        iv_postFood.setOnClickListener(this);

        iv_goodsGoBack.setOnClickListener(this);
        tv_topRight.setOnClickListener(this);

        pictureSelectPopupWindow = new PictureSelectPopupWindow(this, pictureSelectItemsOnClick);
        pictureHandlePopupWindow = new PictureHandlePopupWindow(this, pictureHandleItemsOnClick);
        pictureSelectPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pictureSelectPopupWindow.backgroundAlpha(1.0f);
            }
        });
        pictureHandlePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pictureHandlePopupWindow.backgroundAlpha(1.0f);
            }
        });
    }

    View.OnClickListener pictureSelectItemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_take_photo:   // 调用系统相机
                    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(camera, REQUESTCODE_CAMERA);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_pick_photo:   // 调取手机相册
                    Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(picture, REQUESTCODE_PICTURE);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_cancel:   // 取消
                    pictureSelectPopupWindow.dismiss();
                    break;
            }
        }
    };

    View.OnClickListener pictureHandleItemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_big_picture:
                    pictureHandlePopupWindow.dismiss();
                    Bundle bundle = new Bundle();
                    if (TAG == 1) {
                        Dlog.e(pic_1);
                        if (picAisFromNet) {
                            bundle.putString("img_path", Config.img_url + pic_1);
                        } else {
                            bundle.putString("img_path", pic_1);
                        }
                        overlay(ImageShowerActivity.class, bundle);
                    } else if (TAG == 2) {
                        Dlog.e(pic_2);
                        if (picBisFromNet) {
                            bundle.putString("img_path", Config.img_url + pic_2);
                        } else {
                            bundle.putString("img_path", pic_2);
                        }
                        overlay(ImageShowerActivity.class, bundle);
                    } else if (TAG == 3) {
                        Dlog.e(pic_3);
                        if (picCisFromNet) {
                            bundle.putString("img_path", Config.img_url + pic_3);
                        } else {
                            bundle.putString("img_path", pic_3);
                        }
                        overlay(ImageShowerActivity.class, bundle);
                    } else if (TAG == 4) {
                        Dlog.e(pic_4);
                        if (picDisFromNet) {
                            bundle.putString("img_path", Config.img_url + pic_4);
                        } else {
                            bundle.putString("img_path", pic_4);
                        }
                        overlay(ImageShowerActivity.class, bundle);
                    }
                    break;
                case R.id.btn_delete: // 删除图片
                    pictureHandlePopupWindow.dismiss();
                    deleteImage();
                    break;
                case R.id.btn_cancel:
                    pictureHandlePopupWindow.dismiss();
                    break;
            }
        }
    };

    //删除图片
    public void deleteImage() {
        if (TAG == 1) {
            pic_1 = "";
            iv_postYingye.setImageResource(R.drawable.ic_addpicture);
        } else if (TAG == 2) {
            pic_2 = "";
            iv_postDoor.setImageResource(R.drawable.ic_addpicture);
        } else if (TAG == 3) {
            pic_3 = "";
            iv_environment.setImageResource(R.drawable.ic_addpicture);
        } else if (TAG == 4) {
            pic_4 = "";
            iv_postFood.setImageResource(R.drawable.ic_addpicture);
        }
    }

    private void initData() {
        shopInfo = (ShopInfo) getIntent().getSerializableExtra("shopInfo");
        goodsClass = (GoodsClass) getIntent().getSerializableExtra("goodsClass");
        String pic_a = shopInfo.getPic_a();
        String pic_b = shopInfo.getPic_b();
        String pic_c = shopInfo.getPic_c();
        String pic_d = shopInfo.getPic_d();
        if (!TextUtils.isEmpty(pic_a)) {
            picAisFromNet = true;
            pic_1 = pic_a;
            x.image().bind(iv_postYingye, Config.img_url + pic_a);
        }
        if (!TextUtils.isEmpty(pic_b)) {
            picBisFromNet = true;
            pic_2 = pic_b;
            x.image().bind(iv_postDoor, Config.img_url + pic_b);
        }
        if (!TextUtils.isEmpty(pic_c)) {
            picCisFromNet = true;
            pic_3 = pic_c;
            x.image().bind(iv_environment, Config.img_url + pic_c);
        }

        if (goodsClass != null) {
            tv_type.setText(goodsClass.getName());
            if ("11".equals(goodsClass.getId())) {
                ll_foodCard.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(pic_d)) {
                    picDisFromNet = true;
                    pic_4 = pic_d;
                    x.image().bind(iv_postFood, Config.img_url + pic_d);
                }
            } else {
                ll_foodCard.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_goodsGoBack:
                finish();
                break;
            case R.id.iv_postYingye:
                TAG = 1;
                if (TextUtils.isEmpty(pic_1)) {
                    pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_shop_aptitude), Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                } else {
                    pictureHandlePopupWindow.showAtLocation(findViewById(R.id.activity_shop_aptitude), Gravity.BOTTOM, 0, 0);
                    pictureHandlePopupWindow.backgroundAlpha(0.5f);
                }
                break;
            case R.id.iv_postFood:
                TAG = 4;
                if (TextUtils.isEmpty(pic_4)) {
                    pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_shop_aptitude), Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                } else {
                    pictureHandlePopupWindow.showAtLocation(findViewById(R.id.activity_shop_aptitude), Gravity.BOTTOM, 0, 0);
                    pictureHandlePopupWindow.backgroundAlpha(0.5f);
                }
                break;
            case R.id.iv_postDoor:
                TAG = 2;
                if (TextUtils.isEmpty(pic_2)) {
                    pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_shop_aptitude), Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                } else {
                    pictureHandlePopupWindow.showAtLocation(findViewById(R.id.activity_shop_aptitude), Gravity.BOTTOM, 0, 0);
                    pictureHandlePopupWindow.backgroundAlpha(0.5f);
                }
                break;
            case R.id.iv_environment:
                TAG = 3;
                if (TextUtils.isEmpty(pic_3)) {
                    pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_shop_aptitude), Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                } else {
                    pictureHandlePopupWindow.showAtLocation(findViewById(R.id.activity_shop_aptitude), Gravity.BOTTOM, 0, 0);
                    pictureHandlePopupWindow.backgroundAlpha(0.5f);
                }
                break;
            case R.id.tv_topRight:
                uploadPic();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == REQUESTCODE_PICTURE && resultCode == RESULT_OK) {
//                Uri selectedImage = data.getData();
                Uri selectedImage = geturi(data);
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                if (c != null) {
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    String picturePath = c.getString(columnIndex);
                    c.close();
                    //添加图片
                    addImages(picturePath);
                }

            }
            if (requestCode == REQUESTCODE_CAMERA && resultCode == RESULT_OK) {
                String sdState = Environment.getExternalStorageState();
                if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                    Dlog.e("sd card unmount");
                }
                String name = UUID.randomUUID().toString() + ".jpg";
                File file = new File("/sdcard/pintu");
                file.mkdirs();
                Bundle bundle = data.getExtras();
                //获取相机返回的数据，并转换为图片格式
                Bitmap bitmap = (Bitmap) bundle.get("data");
                FileOutputStream fout = null;
                String fileName = file.getPath() + name;
                try {
                    fout = new FileOutputStream(fileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                    addImages(fileName);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fout.flush();
                        fout.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    //添加图片
    public void addImages(String path) {
        switch (TAG) {
            case 1:
                pic_1 = path;
                picAisFromNet = false;
                x.image().bind(iv_postYingye, pic_1);
                break;
            case 2:
                pic_2 = path;
                picBisFromNet = false;
                x.image().bind(iv_postDoor, pic_2);
                break;
            case 3:
                pic_3 = path;
                picCisFromNet = false;
                x.image().bind(iv_environment, pic_3);
                break;
            case 4:
                pic_4 = path;
                picDisFromNet = false;
                x.image().bind(iv_postFood, pic_4);
                break;
        }
    }

    /**
     * 上传图片
     */
    private void uploadPic() {
        File picA = new File(pic_1);
        File picB = new File(pic_2);
        File picC = new File(pic_3);
        File picD = new File(pic_4);
//        Dlog.e(picA + ";" + picB + ";" + picC + ";" + picD);
        showCustomLoadBar(".");
        RequestParams params = new RequestParams(Config.personal_pic_modify);
        params.addBodyParameter("id", user.getUser_id());
        if (!picA.isFile()) {
            picA = null;
        } else {
            Dlog.e("执行了picA");
            Dlog.e(picA + "");
            params.addBodyParameter("pic_a", picA);
        }
        if (!picB.isFile()) {
            picB = null;

        } else {
            Dlog.e("执行了picB");
            Dlog.e(picB + "");
            params.addBodyParameter("pic_b", picB);
        }
        if (!picC.isFile()) {
            picC = null;

        } else {
            Dlog.e("执行了picC");
            Dlog.e(picC + "");
            params.addBodyParameter("pic_c", picC);
        }
        if (!picD.isFile()) {
            picD = null;

        } else {
            Dlog.e("执行了picD");
            Dlog.e(picD + "");
            params.addBodyParameter("pic_d", picD);
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if (0 == errCode) {
                    sendModifySuccessBroadcast();
                    finish();
                }
                toast(errMsg);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    private void sendModifySuccessBroadcast() {
        Intent intent = new Intent();
        intent.setAction(Constant.ACTION_UPDATE_PIC);
        sendBroadcast(intent);
    }

    /**
     * 解决小米部分手机调用系统相册失败
     *
     * @param intent
     * @return
     */

    public Uri geturi(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }
}
